import React, { Component, useState, useRef, useEffect } from 'react';
import { connect } from 'umi';
import axios from 'axios'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import PersonInfo from './components/personInfo';
import { Button, Table, Divider, Dropdown, Menu, message, Form, Input, Select, Switch, Modal, Alert, Descriptions, Upload, InputNumber, Tooltip } from 'antd';
import { UploadOutlined, SearchOutlined } from '@ant-design/icons';
import { changestatus, resetPassword, importExcel, getCurrent, searchclass } from './service';
import Authorized from '@/utils/Authorized';
const { Option } = Select
const { Search } = Input;

/**
 * 添加节点
 * @param fields
 */

// const noMatch = <Alert message='权限不足' type='error' showIcon closable />
const noMatch = ''
const Tablelist = (props) => {
    const {
        loading,
        dispatch,
        listAndbasicList1: { list },
    } = props;
    console.log(list)
    const [resetpassvisible, setpassvisible] = useState(false);//重置密码弹框
    const [createModalVisible, handleModalVisible] = useState(false);//新建用户弹框
    const [gradeVisible, setgradeVisible] = useState(false);//成绩查询弹框
    const [personVisible, setpersonVisible] = useState(false);//个人信息弹框
    const [updateModalVisible, handleUpdateModalVisible] = useState(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);//选择列表
    const [detail, setdetail] = useState({});//修改个人数据
    const [current, setCurrent] = useState(null);//新建和编辑共用一个弹窗
    const [gradeCurrent, setgradeCurrent] = useState(null);//成绩弹框
    const [classdata, setclassdata] = useState([]);//搜索班级
    const [url, seturl] = useState('');//搜索班级
    let query = useRef({
        pageIndex: 1,
        pageSize: 20,
        grade: "",
        classId: "",
        username: "",
        type: "",
        status: "",
        order: "id desc"
    })
    let passid = useRef()
    useEffect(() => {
        seturl(window.location.host)
        dispatch({
            type: 'listAndbasicList1/fetch',
            payload: {
                ...query.current
            },
        });
    }, [1]);
    const paginationProps = {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSize: query.current.pageSize,
        total: list.total,
        onChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            console.log(query.current)
            dispatch({
                type: 'listAndbasicList1/fetch',
                payload: {
                    ...query.current
                },
            });
            //   console.log(page,currents,pageSize,pagination)            
        },

        onShowSizeChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            dispatch({
                type: 'listAndbasicList1/fetch',
                payload: {
                    ...query.current
                },
            });
        }
    };
    // 可以提交用户增加编辑信息
    const handleAdd = values => {
        console.log(values, current)
        const id = current ? current.id : undefined;
         dispatch({
            type: 'listAndbasicList1/submit',
            payload: {
                id,
                status: 0,
                ...values,
            },
        });
        //存在问题,更新数据和请求列表同时执行。可能在更新数据前就执行了这个刷新列表接口，导致数据没及时更新
        // dispatch({
        //     type: 'listAndbasicList1/fetch',
        //     payload: {
        //         ...query.current
        //     },
        // });

    };
    const handleCancel = values => {
        handleModalVisible(false)
    }
    const actionRef = useRef();
    // 搜索班级
    const fetchdata = async value => {
        const datas = await searchclass({ name: value })
        setclassdata(datas.data)


    };
    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            defaultSortOrder: 'descend',
            sorter: (a, b) => a.id - b.id,
            render: (text, record, index) => {
                return (<a >{record.username}</a>
                )
            }
        },
        {
            title: '真实姓名',
            dataIndex: 'name',
        },
        {
            title: '所属角色',
            dataIndex: 'type',
            render: val => {
                var ty;
                if (val === 1) {
                    ty = '高级教师'
                } else if (val == 2) {
                    ty = '普通教师'
                } else if (val == 3) {
                    ty = '学生'
                } else {
                    ty = '超管'
                }
                return ty
            },

        },
        {
            title: '学号/工号',
            dataIndex: 'student_number',
        },
        {
            title: '年纪',
            dataIndex: 'class_grade',
        },
        {
            title: '班级',
            dataIndex: 'class_name',
        },

        {
            title: '状态',
            dataIndex: 'status',
            render: (text, record, index) => {
                return (
                    <Authorized authority={['admin']} noMatch={noMatch}> 
                     <Switch checkedChildren='开启' unCheckedChildren="关闭" checked={record.status === 0 ? 1 : 0} onChange={(value) => {
                    changeswitch(value, record)
                }} />
                    </Authorized>
               )
            }
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <Authorized authority={['admin', 'admin1', 'user']} noMatch={noMatch} >
                        <a onClick={() => { setgradeVisible(true); getcurrent(record); }}>成绩查询</a>
                    </Authorized>
                    <Divider type="vertical" />
                    {/* 和新建界面一样，用同一个组件，这不过这个根据ID打开那边要获取值 */}
                    <Authorized authority={['admin']} noMatch={noMatch} >
                        <a onClick={() => { handleModalVisible(true); setCurrent(record); }}>修改资料</a>
                    </Authorized>
                    <Divider type="vertical" />
                    <Authorized authority={['admin']} noMatch={noMatch} >
                        <a
                            onClick={() => {
                                showModal(true, record);

                            }}
                        >
                            重置密码
                      </a>
                    </Authorized>

                    <Divider type="vertical" />
                    <Authorized authority={['admin']} noMatch={noMatch} >
                        <a onClick={() => { del(record) }}>删除</a>
                    </Authorized>
                </>
            ),
        },
    ];
    const getcurrent = async (record) => {
        setgradeCurrent(record.id)
    }
    //开启开关
    const changeswitch = async (checked, record) => {
        let id = ''
        let a;
        if (record) {
            id = record.id
            if (checked) {//说明位true 
                a = 0
            } else {//说明要关闭 设置为1
                a = 1
            }
        } else {
            //字符串拼接
            id = selectedRowKeys.join(',')
            a = checked
        }
        console.log(checked, record)

        let res = await changestatus({ id: id, status: a })
        if (res.code == 200) {
            dispatch({
                type: 'listAndbasicList1/fetch',
                payload: {
                    ...query.current
                },
            });
        }
        console.log(list)
    }
    // 删除
    const deleteItem = id => {
        dispatch({
            type: 'listAndbasicList1/submit',
            payload: {
                id,
            },
        });


    };
    const del = (currentItem) => {
        let str = ''
        if (currentItem) {
            str = currentItem.id
        } else {
            //字符串拼接
            if (selectedRowKeys.length==0) {
                message.error('当前没有选中用户')
                return

            }
            str = selectedRowKeys.join(',')
           
        }

        let content = currentItem? `删除的账户无法恢复，若非导入错误，建议使用账户冻结功能。\n确定要删除 ${currentItem.username} 账户吗？` : `本次选中 ${selectedRowKeys.length} 个账户，删除的账户无法恢复，若非导入错误，建议使用账户冻结功能。\n确定要删除吗？`
        console.log(str, currentItem)
        Modal.confirm({
            title: '删除任务',
            content: content,
            okText: '确认',
            cancelText: '取消',
            onOk: () => deleteItem(str),
        });
    }

    // 导入
    const uploadprops = {

        // 这里我们只接受excel2007以后版本的文件，accept就是指定文件选择框的文件类型
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        name: 'file',
        progress:{ strokeWidth: 2, showInfo: false },
        showUploadList: false,
        beforeUpload: async file => {
            let config = {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': `${sessionStorage.getItem('tokenHead')} ${sessionStorage.getItem('token')}`,
                },
            }
            const formData = new FormData();
            formData.append('file', file);
            axios.post('/admin/importExcel', formData, config)
                .then(res => {
                    if (res.data.code == 200) {
                        message.success(`${file.name} 导入成功`);
                        dispatch({
                            type: 'listAndbasicList1/fetch',
                            payload: {
                                ...query.current
                            },
                        });
                    } else {
                        message.error(res.data.message);
                    }
                    console.log(res)
                })
                .catch(error => {
                    message.error(`${file.name} 导入失败.`);
                });
            // let res =await importExcel(formData)
            // console.log(formData.get('file'),file,res)
            // console.log(11111111111)
        },

    };
    // 重置密码弹窗操作
    const showModal = (trues, record) => {
        setpassvisible(trues)
        passid.current = record
    };

    const hideModal = async () => {
        console.log(passid.current)
        setpassvisible(false)
        // 提交id
        await resetPassword({ id: passid.current.id })
    };
    //   个人信息弹窗
    const showpersonModal = () => {
        setpersonVisible(true)
    };

    const hidepersonModal = () => {
        setpersonVisible(false)

    };
    // 提示
    const onClose = (e) => {
        console.log(e, 'I was closed.');
    };

    //筛选数据
    const onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        setSelectedRowKeys(selectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    // const onGenderChange = value => {
    //     form.current.setFieldsValue({
    //         note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
    //     });
    // };
    const [form] = Form.useForm();
    const onFinish = async (values) => {
        const fieldsValue = await form.validateFields();
        console.log(form,fieldsValue)
        // form.resetFields();需要重置
        // 利用父组件传递过来的方法，顺便传此子组件的值。进行调用
        // handleAdd(fieldsValue);
        query.current = { ...query.current, ...fieldsValue }
        dispatch({
            type: 'listAndbasicList1/fetch',
            payload: {
                ...query.current
            },
        });
    };
    const layout = {
        labelCol: {
            span: 10,
        },
        wrapperCol: {
            span: 10,
        },
    };
    return (
        <PageHeaderWrapper>
            <div >
                <Modal
                    title="重置密码"
                    visible={resetpassvisible}
                    onOk={() => hideModal(false)}
                    onCancel={() => hideModal(false)}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>“学生密码重置为学号，教师密码重置为123456，确定要重置账户 [账号 姓名 账户类型] 的密码吗？”</p>
                </Modal>
                {/* 个人信息弹窗 */}
                <Modal
                    title="个人信息"
                    visible={personVisible}
                    onOk={() => hidepersonModal(false)}
                    onCancel={() => hidepersonModal(false)}
                    okText="确认"
                    cancelText="取消"
                >
                    <Descriptions title="若信息有误请联系管理员" size='small'>
                        <Descriptions.Item label="账号">Cloud Database</Descriptions.Item>
                        <Descriptions.Item label="姓名" span={2}>Prepaid</Descriptions.Item>
                        <Descriptions.Item label="类型" >18:00:00</Descriptions.Item>
                        <Descriptions.Item label="工号">$80.00</Descriptions.Item>
                    </Descriptions>
                </Modal>

                <PersonInfo
                    currentinfo={gradeCurrent}
                    onCancel={() => setgradeVisible(false)}
                    modalVisible={gradeVisible}
                />
                <Form layout='inline'>
                    <Form.Item label="">
                        <Authorized authority={['admin']} noMatch={noMatch}>
                            <Button type="primary" onClick={() => { handleModalVisible(true); setCurrent(null) }}>新建</Button>
                        </Authorized>
                        {/* 增加 */}
                        {/* createform子组件 通过属性的方式传递本地父组件的增加方法和本地值 */}
                        <CreateForm
                            onSubmit={handleAdd}
                            onCancel={handleCancel}
                            current={current}
                            modalVisible={createModalVisible}
                        />
                    </Form.Item>
                    <Form.Item label="">
                        <Authorized authority={['admin']} noMatch={noMatch}>
                            <Button type="primary" onClick={() => { changeswitch(0) }}>启用</Button>
                        </Authorized>
                    </Form.Item>
                    <Form.Item label="">
                        <Authorized authority={['admin']} noMatch={noMatch} >  <Button type="primary" onClick={() => { changeswitch(1) }}>禁用</Button>
                        </Authorized>
                    </Form.Item>
                    <Form.Item label="">
                        <Authorized authority={['admin']} noMatch={noMatch}> <Button type="primary" onClick={() => { del() }}>删除</Button>
                        </Authorized>
                    </Form.Item>
                    <Form.Item label="">
                        <Authorized authority={['admin']} noMatch={noMatch}>
                            <Upload {...uploadprops}>
                                <Button type="primary">
                                    <UploadOutlined /> 教师导入
                           </Button>
                            </Upload>
                        </Authorized>

                    </Form.Item>
                    <Form.Item label="">
                        <Button type="primary" >
                       
                            <a href={`http://${url}/账户数据导入.xls`}>模板</a>

                        </Button>
                    </Form.Item>

                </Form>
            </div>
            <div style={{ marginTop: "50px", marginBottom: "20px" }}>
                <Form {...layout} layout='inline' form={form} name="control-ref" >
                    <Form.Item
                        style={{ width: '200px' }}
                        name="grade"
                        label="年级"

                    >
                        <InputNumber min={1}
                            defaultValue={3}
                            formatter={value => `${value}`}
                            parser={value => value.replace(/[^\d]/g, '')}
                            precision={0} />
                    </Form.Item>
                    <Form.Item
                        style={{ width: '200px' }}
                        name="status"
                        label="状态"

                    >
                        <Select
                            placeholder=""
                            allowClear
                            style={{ width: '120%' }}
                        >
                            <Option value="0">正常</Option>
                            <Option value="1">冻结</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        style={{ width: '200px' }}
                        name="type"
                        label="所属角色"

                    >
                        <Select
                            placeholder=""
                            allowClear
                            style={{ width: '120%' }}
                        >
                            <Option value="0">超管</Option>
                            <Option value="1">高级教师</Option>
                            <Option value="2">教师</Option>
                            <Option value="3">学生</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        style={{ width: '200px' }}
                        name="classId"
                        label="班级"

                    >

                        <Select
                            showSearch
                            allowClear
                            placeholder="可搜索"
                            filterOption={false}
                            onSearch={fetchdata}
                            style={{ width: '120%' }}
                        >
                            {classdata.map(d => (
                                <Option key={d.id} value={d.id}>{d.class_name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        style={{ width: '200px' }}
                        name="username"
                        label="关键字"

                    >
                     <Search placeholder="姓名，学号/工号，用户名"  onSearch={onFinish} enterButton  style={{ width: 200 }}/>
                        {/* <Input
                            placeholder=""                           
                            style={{ width: 200 }}
                        />
                        <Button type="primary" shape="circle" style={{ position: 'relative', right: '-155px', top: "-30px" }} icon={<SearchOutlined />} onClick={onFinish} /> */}

                    </Form.Item>

                </Form>
            </div>
            <Alert
                message='任何用户不能编辑自己的数据，如需修改，请联系管理员'
                type="warning"
                closable
                onClose={onClose}
            />
            <Table rowSelection={rowSelection} columns={columns} dataSource={list.list} pagination={paginationProps} rowKey={record => record.id} />
        </PageHeaderWrapper>
    )

}
export default connect(({ listAndbasicList1, loading }) => ({
    listAndbasicList1,
    loading: loading.models.listAndbasicList1,
}))(Tablelist);
